package com.adresvseti.wallpaperoid.utils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.graphics.BitmapFactory;

public class BitmapUtil {

	
	/** Calculates ratio to inscribe into required size.
	 * @param options					Bitmap options.
	 * @param targetWidth				Required maximum width. 
	 * @param targetHeight				Required maximum height.
	 * @return							Resizing ratio.
	 */
	public static int calculateInSampleSize(BitmapFactory.Options options, int targetWidth, int targetHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > targetHeight || width > targetWidth) {

			// Calculate ratios of height and width to requested height and width
			final int heightRatio = Math.round((float) height / (float) targetHeight);
			final int widthRatio = Math.round((float) width / (float) targetWidth);

			// Choose the smallest ratio as inSampleSize value, this will guarantee
			// a final image with both dimensions larger than or equal to the
			// requested height and width.
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}
		
		return inSampleSize;
	}
	
	
	/** Reads InputStream as byte array.
	 * @param is	Input stream.
	 * @return		Bytes from input stream.
	 * @throws IOException
	 */
	public static byte[] convertInputStreamToByteArray(InputStream is) throws IOException
	{
		BufferedInputStream bis = new BufferedInputStream(is);
		ByteArrayOutputStream buf = new ByteArrayOutputStream();
		int result = bis.read();
		while(result !=-1)
		{
			byte b = (byte)result;
			buf.write(b);
			result = bis.read();
		}
		return buf.toByteArray();
	}
	
}
